<?php

namespace App\Http\Controllers\Admin\SystemSet\ParamsManager;

use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;    //引用http请求类
use App\Response\Response;

class ParamsManagerController extends BaseController {

    /**
     * @api {post} /system-set/params-manager 参数管理-创建参数
     * @apiVersion 0.1.0
     * @apiName 系统设置-参数管理-创建参数
     * @apiGroup 系统设置
     *
     * @apiParam {string} key                       配置标识 必传
     * @apiParam {number} group                     配置分组 必传
     * @apiParam {number} type                      配置类型 必传
     * @apiParam {string} name                      配置名称 必传
     * @apiParam {string} desc                      配置项说明 选传
     * @apiParam {number} status                    是否启用 1：启用 0：禁用 必传
     * @apiParam {string} value                     配置值 必传
     * @apiParam {number} sort                      排序 必传
     *
     * @apiSuccessExample 成功响应
     *
     *      {"code":200,"data":true}
     *
     * @apiError 10001 参数校验失败
     *
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    public function create(Request $request)
    {
        //参数校验
        try {
            $this->validate($request, [
                'status' => 'required|numeric|integer|in:0,1',
                'key' => 'required|string',
                'group' => 'required|numeric',
                'type' => 'required|numeric',
                'name' => 'required|string',
//                'desc' => 'required|string',
                'value' => 'required|string',
                'sort' => 'required|numeric',
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }

        $groupRes = app('repo_config')->queryConfig('CONFIG_GROUP_LIST');

        $groupMap = empty($groupRes) ? [] : $groupRes->parse();

        if (!empty($request->input("group")) && !isset($groupMap[$request->input("group")])) {
            throw new BasicException(10001, "分组类型不合法！");
        }

        $typeRes = app('repo_config')->queryConfig('CONFIG_TYPE_LIST');

        $typeMap = empty($typeRes) ? [] : $typeRes->parse();

        if (!empty($request->input("type")) && !isset($typeMap[$request->input("type")])) {
            throw new BasicException(10001, "配置类型不合法！");
        }

        $rows = app('repo_config')->addConfig($request->input());
        if (!$rows) {
            throw new BasicException(10001, "更新失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {delete} /system-set/params-manager 参数管理-删除参数
     * @apiVersion 0.1.0
     * @apiName 系统设置-参数管理-删除参数
     * @apiGroup 系统设置
     *
     * @apiParam {string} ids                       字符串分割的id 必传
     *
     * @apiSuccessExample 成功响应
     *
     *      {"code":200,"data":true}
     *
     * @apiError 10001 参数校验失败
     *
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    public function del(Request $request) {
        //参数校验
        try {
            $this->validate($request, [
                'ids' => 'required|string',
            ]);

        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }

        $idsStr = $request->input("ids");
        $idsArr = explode("," , $idsStr);

        $rows = app('repo_config')->batchDelConfig($idsArr);
        if (!$rows) {
            throw new BasicException(10001, "删除失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {put} /system-set/params-manager 参数管理-修改参数
     * @apiVersion 0.1.0
     * @apiName 系统设置-参数管理-修改参数
     * @apiGroup 系统设置
     *
     * @apiParam {string} key                       配置标识 必传
     * @apiParam {number} group                     配置分组 必传
     * @apiParam {number} type                      配置类型 必传
     * @apiParam {string} name                      配置名称 必传
     * @apiParam {string} desc                      配置项说明 选传
     * @apiParam {number} status                    是否启用 1：启用 0：禁用 必传
     * @apiParam {string} value                     配置值 必传
     * @apiParam {number} sort                      排序 必传
     *
     * @apiSuccessExample 成功响应
     *
     *      {"code":200,"data":true}
     *
     * @apiError 10001 参数校验失败
     *
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    public function update(Request $request) {
        //参数校验
        try {
            $this->validate($request, [
                'id' => 'required|integer',
                'status' => 'required|numeric|integer|in:0,1',
                'key' => 'required|string',
                'group' => 'required|numeric',
                'type' => 'required|numeric',
                'name' => 'required|string',
//                'desc' => 'filled|string',
                'value' => 'required|string',
                'sort' => 'required|numeric',
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }
        $id = $request->input('id');

        $groupRes = app('repo_config')->queryConfig('CONFIG_GROUP_LIST');

        $groupMap = empty($groupRes) ? [] : $groupRes->parse();

        if (!empty($request->input("group")) && !isset($groupMap[$request->input("group")])) {
            throw new BasicException(10001, "分组类型不合法！");
        }

        $typeRes = app('repo_config')->queryConfig('CONFIG_TYPE_LIST');

        $typeMap = empty($typeRes) ? [] : $typeRes->parse();

        if (!empty($request->input("type")) && !isset($typeMap[$request->input("type")])) {
            throw new BasicException(10001, "配置类型不合法！");
        }
        $params = $request->input();

        $rows = app('repo_config')->saveConfig(["id" => $id], $params);
        if (!$rows) {
            throw new BasicException(10001, "更新失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {get} /system-set/params-manager/app/version 参数管理-App版本
     * @apiVersion 0.1.0
     * @apiName 系统设置-参数管理-App版本
     * @apiGroup 系统设置
     *
     * @apiParam {number} page 当前页数 可选
     * @apiParam {number} perPage 分页容量 可选
     *
     *
     * @apiSuccessExample 成功响应
     *
     *
    {
        "code": 200,
        "data": {
            "list": [
                {
                    "id(序号)": 116,
                    "key(配置标志)": "USER_RECHARGE_ZERO",
                    "type(配置类型)": 4,
                    "group(配置分组)": 1,
                    "name(配置名称)": "充值只要1分钱的用户",
                    "desc(配置项说明)": "充值只要1分钱的用户；只有测试环境生效",
                    "status(是否启用 1：启用 0：禁用)": 0,
                    "value(配置值)": "302928,652761,232706,617040,888888",
                    "sort(排序)": 0
                }
        ],
        "meta": {
                "page": 1,
                "limit": 10,
                "next": null,
                "total": 1
            }
        }
    }
     *
     *
     */
    public function listVersion(Request $request) {
        //参数校验
        try {
            $this->validate($request, [
                'perPage' => 'filled|numeric',
                'page' => 'filled|numeric',
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }

        $params = $request->input();
        $params['keyword'] = "VERSION";

        $list = app('repo_config')->getQueryList($params);

        return Response::sendList($list);
    }

    /**
     * @api {get} /system-set/params-manager 参数管理-列表页数据
     * @apiVersion 0.1.0
     * @apiName 系统设置-参数管理-列表页数据
     * @apiGroup 系统设置
     *
     * @apiParam {number} page 当前页数 可选
     * @apiParam {number} perPage 分页容量 可选
     * @apiParam {number} group_type 分组类型 可选
     * @apiParam {string} keyword 搜索关键字 可选
     *
     *
     * @apiSuccessExample 成功响应
     *
     *
    {
    "code": 200,
    "data": {
        "list": [
            {
                "id(序号)": 116,
                "key(配置标志)": "USER_RECHARGE_ZERO",
                "type(配置类型)": 4,
                "group(配置分组)": 1,
                "name(配置名称)": "充值只要1分钱的用户",
                "desc(配置项说明)": "充值只要1分钱的用户；只有测试环境生效",
                "status(是否启用 1：启用 0：禁用)": 0,
                "value(配置值)": "302928,652761,232706,617040,888888",
                "sort(排序)": 0
            }
        ],
        "meta": {
                "page": 1,
                "limit": 10,
                "next": null,
                "total": 1
            }
        }
    }
     *
     *
     */
    public function list(Request $request) {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'perPage' => 'filled|numeric',
                'page' => 'filled|numeric',
                'keyword' => 'filled|string',
                'group_type' => 'filled|numeric',
            ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $typeRes = app('repo_config')->queryConfig('CONFIG_GROUP_LIST');

        $typeMap = empty($typeRes) ? [] : $typeRes->parse();

        if (!empty($request->input("group_type")) && !isset($typeMap[$request->input("group_type")])) {
            throw new BasicException(10001, "配置类型不合法！");
        }

        $list = app('repo_config')->getQueryList($request->input());

        return Response::sendList($list);
    }

    /**
     * @api {get} /system-set/params-manager/type/map 参数管理-获取参数配置类型
     * @apiVersion 0.1.0
     * @apiName 系统设置-参数管理-获取参数配置类型
     * @apiGroup 系统设置
     *
     *
     * @apiSuccessExample 成功响应
     *
     *
    {
        "code": 200,
        "data": {
            "type_map(值类型映射)": [
                "数字",
                "字符",
                "文本",
                "枚举",
                "数组"
            ],
            "group_map(分组类型映射)": {
                "1": "基本设置",
                "15": "短信接口",
                "30": "APP消息推送",
                "40": "系统参数",
                "60": "程序员设置",
                "65": "返利设置",
                "100": "项目设置"
            }
        }
    }
     *
     *
     */
    public function typeList(Request $request) {
        $groupRes = app('repo_config')->queryConfig('CONFIG_GROUP_LIST');

        $groupResult = empty($groupRes) ? new \stdClass() : $groupRes->parse();

        $typeRes = app('repo_config')->queryConfig('CONFIG_TYPE_LIST');

        $typeResult = empty($typeRes) ? new \stdClass() : $typeRes->parse();

        $result = [
            "type_map" => $typeResult,
            "group_map" => $groupResult,
        ];

        return Response::sendData($result);
    }

}
